package com.imooc.reader.controller.management;


import com.imooc.reader.enity.Member;
import com.imooc.reader.service.MemberService;
import com.imooc.reader.service.exception.BussinessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 后台管理系统控制器
 */
@Controller
@RequestMapping("/management")
public class ManagementController {
    @Resource
    MemberService memberService;

    /**
     * 后台首页
     * @return
     */
    @GetMapping("/index.html")
    public ModelAndView showIndex(){
        return new ModelAndView("/management/index");
    }

    /**
     * 后台登陆界面,登出界面
     * @return
     */
    @GetMapping(value={"/login.html","/logout"})
    public ModelAndView showLogin(HttpServletRequest request,HttpSession session){
        String url = request.getRequestURI();
        String substring = url.substring(url.lastIndexOf("/"));
        if("/logout".equals(substring)){
            session.removeAttribute("loginManagementMember");
        }
        return new ModelAndView("/management/login");
    }


    /**
     * 后台登陆
     * @param username
     * @param password
     * @param request
     * @param session
     * @return
     */
    @PostMapping ("/check_login")
    @ResponseBody
    public Map checkLogin(String username, String password, HttpServletRequest request, HttpSession session){
        Map result = new HashMap();
        try {
            Member member = memberService.checkLogin(username, password);
            session.setAttribute("loginManagementMember",member);
            result.put("code","0");
            result.put("msg","success");
        }catch (BussinessException ex){
            ex.printStackTrace();
            result.put("code",ex.getCode());
            result.put("msg",ex.getMsg());
        }
        return result;
    }

}

